package com.qding.park.manager.web.controller;

import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.validation.Valid;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.qding.park.common.core.annotation.log.OperationLogType;
import com.qding.park.common.core.annotation.log.SystemControllerLog;
import com.qding.park.common.utils.DateUtils;
import com.qding.park.common.utils.ListUtil;
import com.qding.park.common.utils.export.DataField;
import com.qding.park.common.utils.export.ExportDataSource;
import com.qding.park.common.utils.export.excel.ExcelDataExportor;
import com.qding.park.common.utils.export.excel.MODE;
import com.qding.park.common.utils.string.StringUtil;
import com.qding.park.common.web.controller.BaseController;
import com.qding.park.manager.common.pojo.ParkDataResult;
import com.qding.park.manager.common.rest.domain.AnswerMsg;
import com.qding.park.manager.common.rest.domain.AnswerMsgFactoryImpl;
import com.qding.park.manager.facade.statis.service.StatisticsReportFacade;
import com.qding.park.manager.pojo.PowerInfo;
import com.qding.park.manager.pojo.example.StatisInterDayExample;
import com.qding.park.manager.pojo.example.StatisInterMonthExample;
import com.qding.park.manager.pojo.example.StatisPassDayExample;
import com.qding.park.manager.pojo.example.StatisPassMonthExample;
import com.qding.park.manager.web.conf.SystemConfig;
import com.qding.park.manager.web.form.StatisInterDayForm;
import com.qding.park.manager.web.form.StatisInterMonthExportForm;
import com.qding.park.manager.web.form.StatisInterMonthForm;
import com.qding.park.manager.web.form.StatisPassDayForm;
import com.qding.park.manager.web.form.StatisPassMonthExportForm;
import com.qding.park.manager.web.form.StatisPassMonthForm;
import com.qding.park.manager.web.power.Power;

@RestController
@RequestMapping("/statistics")
public class Web_StatisticsController extends BaseController {
    private static final Logger _log = LoggerFactory.getLogger(Web_StatisticsController.class);
	
	@Autowired
	private  StatisticsReportFacade   statisticsReportFacade;
	
	@Autowired
	private  SystemConfig  systemConfig;
	
	@Power(visitPark="#form.getParkId()")
	@SystemControllerLog(description = "通行日报表查询", operation = OperationLogType.statistics_pass_day_list)
	@RequestMapping("/pass/day")
	public AnswerMsg  pass_day(@Valid StatisPassDayForm form,BindingResult result){
		/*解析验证结果*/
		super.analysisValid(result);
		/*解析验证结果*/
		PowerInfo power = this.getPowerInfo();
		
		StatisPassDayExample  example=new StatisPassDayExample();
		example.setDay(DateUtils.parseDate(form.getDay(), DateUtils.DATE_FORMAT_DATETIME));
		if(!StringUtils.isBlank(form.getParkId())){
			example.setParkId(Integer.valueOf(form.getParkId()));
		}
		if(!power.isAdminIs()){
			//非管理员权限
			example.setInParks(power.getParkList());
		}
		
		ParkDataResult  parkDataResult=statisticsReportFacade.passDay(example);
		AnswerMsg answerMsg = AnswerMsgFactoryImpl.createAnswerMsg(parkDataResult.getData());
		return answerMsg;
		
	}
	
	
	@Power(visitPark="#form.getParkId()")
	@SystemControllerLog(description = "通行月报表查询", operation = OperationLogType.statistics_pass_month_list)
	@RequestMapping("/pass/month")
	public AnswerMsg  pass_month(@Valid StatisPassMonthForm form,BindingResult result){
		/*解析验证结果*/
		super.analysisValid(result);
		/*解析验证结果*/
		PowerInfo power = this.getPowerInfo();
		
		StatisPassMonthExample example=new StatisPassMonthExample();
		
		if(!StringUtils.isBlank(form.getParkId())){
			example.setParkId(Integer.valueOf(form.getParkId()));
		}
		if(!StringUtils.isBlank(form.getStartTime())){
			example.setStartTime(DateUtils.parseDate(form.getStartTime(), DateUtils.DATE_FORMAT_DATETIME));
		}
		if(!StringUtils.isBlank(form.getEndTime())){
			example.setEndTime(DateUtils.parseDate(form.getEndTime(), DateUtils.DATE_FORMAT_DATETIME));
		}
		if(!power.isAdminIs()){
			//非管理员权限
			example.setInParks(power.getParkList());
		}
		ParkDataResult  parkDataResult=statisticsReportFacade.passMonth(example,Integer.valueOf(form.getJumpPage()),Integer.valueOf(form.getPageLength()));
		AnswerMsg answerMsg = AnswerMsgFactoryImpl.createAnswerMsg(parkDataResult.getData());
		return answerMsg;
		
		
		
//		long total =Integer.valueOf(form.getPageLength());
//		total=0;
//		List dataList = new ArrayList();
//		for (int i=0;i<total;i++) {
//			Map<String, Object> map = new HashMap<String, Object>();
//			map.put("freeCarNum", 2);
//			map.put("inCheckNum", 11);
//			map.put("inManualNum", 22);
//			map.put("monthFee", 333330000);
//			map.put("monthShouldFee", 333330000);
//			map.put("operator", "雷阳");
//			map.put("outCheckNum", 2222);
//			
//			map.put("outManualNum", 2222);
//			map.put("parkFee", 2222);
//			map.put("parkName", "千丁车场");
//			map.put("totalFee", 33333000);
//			map.put("workTime",60*60*60L);
//			map.put("timeStr","2017-01-01");
//			dataList.add(map);
//		}
//		Map<String, Object> data = new HashMap<String, Object>();
//		data.put("list", dataList);
//		data.put("currentPage", Integer.valueOf(form.getJumpPage()));
//		data.put("numPerPage", Integer.valueOf(form.getPageLength()));
//		data.put("totalCount", total);
//		data.put("hast", Integer.valueOf(form.getJumpPage()) > 1 ? true : false);
//		data.put("next", Integer.valueOf(form.getPageLength()) * Integer.valueOf(form.getJumpPage()) < total ? true : false);
//
//		ParkDataResult parkDataResult = ParkDataResult.createObjDate();
//		parkDataResult.putMapOnObj(data);
//		
//		AnswerMsg answerMsg = AnswerMsgFactoryImpl.createAnswerMsg(parkDataResult.getData());
//		return answerMsg;
	}
	
	
	@Power(visitPark="#form.getParkId()")
	@SystemControllerLog(description = "通行月报表导出", operation = OperationLogType.statistics_pass_month_export)
	@RequestMapping("/pass/month_export")
	@ResponseBody
	public AnswerMsg  pass_month_export(@Valid StatisPassMonthExportForm form,BindingResult result) throws IOException{
		/*解析验证结果*/
		super.analysisValid(result);
		/*解析验证结果*/
		
		PowerInfo power = this.getPowerInfo();
		
		final StatisPassMonthExample example=new StatisPassMonthExample();
		if(form.getStartTime()!=null){
			example.setStartTime(DateUtils.parseDate(form.getStartTime(), DateUtils.DATE_FORMAT_DATETIME));
		}
		if(form.getEndTime()!=null){
			example.setEndTime(DateUtils.parseDate(form.getEndTime(), DateUtils.DATE_FORMAT_DATETIME));
		}
		if(!StringUtils.isBlank(form.getParkId())){
			example.setParkId(Integer.valueOf(form.getParkId()));
		}
		if(!power.isAdminIs()){
			//非管理员权限
			example.setInParks(power.getParkList());
		}
		
		final SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
		final SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		final SimpleDateFormat sdf2 = new SimpleDateFormat("yyyyMMddHHmmss");
		String filename = "通行月报表_" + sdf2.format(new Date());
		response.setHeader("Content-disposition", "attachment; filename=" + URLEncoder.encode(filename + ".xls", "utf-8"));
		OutputStream os = response.getOutputStream();
		DataField[] dataFields = new DataField[13];
		dataFields[0] = new DataField("车场名称", "parkName",40);
		dataFields[1] = new DataField("时间区间", "timeStr",40);
		dataFields[2] = new DataField("操作员", "operator",20);
		dataFields[3] = new DataField("上班时间", "workTime", 20);
		dataFields[4] = new DataField("进场次数", "inCheckNum", 20);
		dataFields[5] = new DataField("出场次数", "outCheckNum", 20);
		dataFields[6] = new DataField("进场手动放行次数", "inManualNum",20);
		dataFields[7] = new DataField("出场手动放行次数", "outManualNum",20);
		dataFields[8] = new DataField("免费车", "freeCarNum",20);
		dataFields[9] = new DataField("停车费", "parkFee",20);
		dataFields[10] = new DataField("月牌应收", "monthShouldFee",20);
		dataFields[11] = new DataField("月牌实收", "monthFee",20);
		dataFields[12] = new DataField("合计", "totalFee",20);
		
		new ExcelDataExportor<Object>(dataFields, new ExportDataSource<Object>() {
			@Override
			public List getData(){
				// 查询统计条件
				List<StatisticsReportFacade.PassMonth>  dataExports=statisticsReportFacade.pass_month_export(example);
				List<Map<String, Object>> lists = new ArrayList<Map<String, Object>>();
					int temp = 0;
					for (int i = 0; i < dataExports.size(); i++) {
						Map<String, Object> mapParam = new HashMap<String, Object>();
						StatisticsReportFacade.PassMonth sttais=dataExports.get(i);
						temp=i;
						mapParam.put("parkName",  StringUtil.isBlank(sttais.getParkName())?"未知":sttais.getParkName());
						mapParam.put("timeStr", sttais.getTimeStr());
						mapParam.put("outManualNum", sttais.getOutManualNum());
						mapParam.put("operator", sttais.getOperator());
						mapParam.put("workTime", sttais.getWorkTime());
						mapParam.put("inCheckNum", sttais.getInCheckNum());
						mapParam.put("outCheckNum", sttais.getOutCheckNum());
						mapParam.put("inManualNum", sttais.getInManualNum());
						mapParam.put("freeCarNum", sttais.getFreeCarNum());
						mapParam.put("parkFee", sttais.getParkFee()/100L);
						mapParam.put("monthShouldFee", sttais.getMonthShouldFee()/100L);
						mapParam.put("monthFee", sttais.getMonthFee()/100L);
						mapParam.put("totalFee", sttais.getTotalFee()/100L);
						lists.add(mapParam);
					}
				return lists;
			}
		}, os, MODE.EXCEL).export();
		AnswerMsg answerMsg = AnswerMsgFactoryImpl.createAnswerMsg(null);
		return answerMsg;
	}
	
	/**
	 * @param form  表单参数
	 * @param result  数据验证结果
	 * @return
	 * 交互日报表统计
	 */
	@Power(visitPark="#form.getParkId()")
	@SystemControllerLog(description = "交互日报表查询", operation = OperationLogType.statistics_inter_day_list)
	@RequestMapping("/inter/day")
	public AnswerMsg inter_day(@Valid StatisInterDayForm form,BindingResult result){
		/*解析验证结果*/
		super.analysisValid(result);
		/*解析验证结果*/
		PowerInfo power = this.getPowerInfo();
		StatisInterDayExample  example=new StatisInterDayExample();
		example.setDay(DateUtils.parseDate(form.getDay(), DateUtils.DATE_FORMAT_DATETIME));
		if(!StringUtils.isBlank(form.getParkId())){
			example.setParkId(Integer.valueOf(form.getParkId()));
		}
		if(!power.isAdminIs()){
			//非管理员权限
			example.setInParks(power.getParkList());
		}
		if(!ListUtil.isEmpty(systemConfig.calculationDemoPark())){
			//排除演示车场
			example.setNoInParks(systemConfig.calculationDemoPark());
		}
		ParkDataResult  parkDataResult=statisticsReportFacade.interDay(example);
		AnswerMsg answerMsg = AnswerMsgFactoryImpl.createAnswerMsg(parkDataResult.getData());
		return answerMsg;

	}
	
	@Power(visitPark="#form.getParkId()")
	@SystemControllerLog(description = "交互月报表查询", operation = OperationLogType.statistics_inter_day_list)
	@RequestMapping("/inter/month")
	public AnswerMsg inter_month(@Valid StatisInterMonthForm form,BindingResult result){
		/*解析验证结果*/
		super.analysisValid(result);
		/*解析验证结果*/
		
		PowerInfo power = this.getPowerInfo();
		
		StatisInterMonthExample example=new StatisInterMonthExample();
		if(!StringUtils.isBlank(form.getStartTime())){
			example.setStartTime(DateUtils.parseDate(form.getStartTime(), DateUtils.DATE_FORMAT_DATETIME));
		}
		if(!StringUtils.isBlank(form.getEndTime())){
			example.setEndTime(DateUtils.parseDate(form.getEndTime(), DateUtils.DATE_FORMAT_DATETIME));
		}
		if(!StringUtils.isBlank(form.getParkId())){
			example.setParkId(form.getParkId());
		}
		if(!power.isAdminIs()){
			//非管理员权限
			example.setInParks(power.getParkList());
		}
		if(!ListUtil.isEmpty(systemConfig.calculationDemoPark())){
			//排除演示车场
			example.setNoInParks(systemConfig.calculationDemoPark());
		}
		int jumpPage=Integer.valueOf(form.getJumpPage());
		int pageLength=Integer.valueOf(form.getPageLength());
		
		ParkDataResult  parkDataResult=statisticsReportFacade.interMonth(example,jumpPage,pageLength);
		AnswerMsg answerMsg = AnswerMsgFactoryImpl.createAnswerMsg(parkDataResult.getData());
		return answerMsg;

	}
	
	
	@Power(visitPark="#form.getParkId()")
	@SystemControllerLog(description = "交互月报表查询", operation = OperationLogType.statistics_inter_day_list)
	@RequestMapping("/inter/month_export")
	@ResponseBody
	public AnswerMsg inter_month_export(@Valid StatisInterMonthExportForm form,BindingResult result) throws IOException{
		
		/*解析验证结果*/
		super.analysisValid(result);
		/*解析验证结果*/
		
		PowerInfo power = this.getPowerInfo();
		
		final StatisInterMonthExample example=new StatisInterMonthExample();
		if(form.getStartTime()!=null){
			example.setStartTime(DateUtils.parseDate(form.getStartTime(), DateUtils.DATE_FORMAT_DATETIME));
		}
		if(form.getEndTime()!=null){
			example.setEndTime(DateUtils.parseDate(form.getEndTime(), DateUtils.DATE_FORMAT_DATETIME));
		}
		if(!StringUtils.isBlank(form.getParkId())){
			example.setParkId(form.getParkId());
		}
		if(!power.isAdminIs()){
			//非管理员权限
			example.setInParks(power.getParkList());
		}
		
		if(!ListUtil.isEmpty(systemConfig.calculationDemoPark())){
			//排除演示车场
			example.setNoInParks(systemConfig.calculationDemoPark());
		}
		
		final SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
		final SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		final SimpleDateFormat sdf2 = new SimpleDateFormat("yyyyMMddHHmmss");
		String filename = "交互月报表_" + sdf2.format(new Date());
		response.setHeader("Content-disposition", "attachment; filename=" + URLEncoder.encode(filename + ".xls", "utf-8"));
		OutputStream os = response.getOutputStream();
		DataField[] dataFields = new DataField[8];
		dataFields[0] = new DataField("车场名称", "parkName",40);
		dataFields[1] = new DataField("时间段", "timeStr",40);
		dataFields[2] = new DataField("车位预定", "reserveNum",20);
		dataFields[3] = new DataField("缴费", "feeNum", 20);
		dataFields[4] = new DataField("车辆邀请", "invitNum", 20);
		dataFields[5] = new DataField("代客缴费", "generaNum", 20);
		dataFields[6] = new DataField("锁车", "carLockNum",20);
		dataFields[7] = new DataField("记录", "hisRecordNum",20);
		
		new ExcelDataExportor<Object>(dataFields, new ExportDataSource<Object>() {
			@Override
			public List getData(){
				// 查询统计条件
				List<StatisticsReportFacade.InterMonth>  dataExports=statisticsReportFacade.inter_month_export(example);
				List<Map<String, Object>> lists = new ArrayList<Map<String, Object>>();
					int temp = 0;
					for (int i = 0; i < dataExports.size(); i++) {
						Map<String, Object> mapParam = new HashMap<String, Object>();
						StatisticsReportFacade.InterMonth sttais=dataExports.get(i);
						temp=i;
						mapParam.put("parkName", StringUtil.isBlank(sttais.getParkName())?"未知":sttais.getParkName());
						mapParam.put("timeStr",sttais.getTimeStr());
						mapParam.put("reserveNum", sttais.getReserveNum());
						mapParam.put("feeNum",sttais.getFeeNum());
						mapParam.put("invitNum", sttais.getInvitNum());
						mapParam.put("generaNum", sttais.getGeneraNum());
						mapParam.put("carLockNum",sttais.getCarLockNum());
						mapParam.put("hisRecordNum",sttais.getHisRecordNum());
						lists.add(mapParam);
					}
				return lists;
			}
		}, os, MODE.EXCEL).export();
		AnswerMsg answerMsg = AnswerMsgFactoryImpl.createAnswerMsg(null);
		return answerMsg;

	}
}
